package com.design.framework.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtils {

	/**
	 * 
	 * 启动成功返回true,否则false
	 * @author JohnDeng
	 * 2018年9月24日上午11:01:48
	 */
	public static boolean startConnectionJedis() {
		boolean startSuccess=true;
		// 获取redis
		Properties prop = new Properties();
		InputStream is = JedisUtils.class.getResourceAsStream("/config/redis.properties");
		try {
			prop.load(is);
		} catch (IOException e1) {
			startSuccess=false;
			e1.printStackTrace();
		}
		String host = prop.getProperty("redis_host");
		int maxIdle = Integer.parseInt(prop.getProperty("redis_maxIdle"));
		int maxTotal = Integer.parseInt(prop.getProperty("redis_maxActive"));
		int minIdle = Integer.parseInt(prop.getProperty("redis.minIdle"));
		boolean testOnBorrow = Boolean.parseBoolean(prop.getProperty("redis_testOnBorrow"));
		int port = Integer.parseInt(prop.getProperty("redis_port"));
		int timeOut = Integer.parseInt(prop.getProperty("redis_timeOut"));
		String password = prop.getProperty("redis_password");
		// 判断是否有连接Reids
		Jedis jedis = null;
		JedisPool jedisPool = null;
		try {
			if (jedisPool == null) {
				JedisPoolConfig config = new JedisPoolConfig();
				config.setMaxIdle(maxIdle);
				config.setMaxTotal(maxTotal);
				config.setMinIdle(minIdle);
				config.setTestOnBorrow(testOnBorrow);
				jedisPool = new JedisPool(config, host, port, timeOut, password);
				jedis = jedisPool.getResource();
			}
			jedis.ping();
		} catch (Exception e) {
			startSuccess=false;
			e.printStackTrace();
		} finally {
			if (jedisPool != null) {
				jedisPool.close();
			}
			if (jedis != null) {
				jedis.close();
			}
		}
		return startSuccess;
	}
}
